package com.hyk.commonLib.common.utils.dataBinding.bindingAdapter;

import android.util.TypedValue;
import android.widget.TextView;

import androidx.databinding.BindingAdapter;

import com.hyk.commonLib.common.utils.rx.EmptyObserver;
import com.jakewharton.rxbinding4.widget.RxTextView;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

/**
 * Created by 贺玉琨 on 2021/1/6.
 */
public class TextViewAdapter {

    private static final int DEBOUNCE_WINDOW_DURATION = 300;

    @BindingAdapter("textSizeInDp")
    public static void setTextSizeInDp(TextView view, double textSize) {
        view.setTextSize(TypedValue.COMPLEX_UNIT_DIP, (float) textSize);
    }

    @BindingAdapter(value = {"onEditorAction", "debounceActionWindow"}, requireAll = false)
    public static void onEditorAction(TextView view, OnEditorActionListener listener, Integer debounceActionWindow) {
        RxTextView.editorActions(view)
                // 防抖操作
                .throttleFirst((debounceActionWindow == null || debounceActionWindow <= 0) ? DEBOUNCE_WINDOW_DURATION : debounceActionWindow, TimeUnit.MILLISECONDS)
                .subscribe(new EmptyObserver<Integer>() {
                    @Override
                    public void onNext(@NotNull Integer actionId) {
                        if (listener != null) {
                            listener.onAction(actionId);
                        }
                    }

                });
    }

    public interface OnEditorActionListener {
        void onAction(@NotNull Integer actionId);
    }
}
